import 'dart:math';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_plugin_record_plus/flutter_plugin_record.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';

typedef startRecord = Future Function();
typedef stopRecord = Future Function();

class YYTVoiceWidget extends StatefulWidget {
  final Function()? startRecord;
  final Function(String? path,num? length)? stopRecord;

  /// startRecord 开始录制回调  stopRecord回调
  const YYTVoiceWidget({Key? key, this.startRecord, this.stopRecord})
      : super(key: key);

  @override
  _VoiceWidgetState createState() => _VoiceWidgetState();
}

class _VoiceWidgetState extends State<YYTVoiceWidget>
    with SingleTickerProviderStateMixin {
  double starty = 0.0;
  double offset = 0.0;
  bool isUp = false;
  String textShow = "按住说话";
  String toastShow = "手指上滑,取消发送";
  String voiceIco = "assets/voice_volume_1.png";
  String _voicePath = '';
  double _audioTimeLength = 0.0;
  List<String> _assetList =  [];
  bool isAnimation = false;

  ///默认隐藏状态
  bool voiceState = true;
  OverlayEntry? overlayEntry;
  // FlutterPluginRecord? recordPlugin;

  ///播放动画 - 动画控制
  Animation<double>? _animation;
  AnimationController? _controller;
  int interval = 200;

  @override
  void dispose() {
    // if (recordPlugin != null) {
    //   recordPlugin?.dispose();
    // }
    _controller?.dispose();
    super.dispose();
  }

  _animationStop() {
    _controller?.stop();
  }

  _animationStart() {
    _controller?.forward();
  }

  @override
  void initState() {
    super.initState();
    // recordPlugin = new FlutterPluginRecord();

    _assetList.add("assets/left_voice_1.png");
    _assetList.add("assets/left_voice_2.png");
    _assetList.add("assets/left_voice_3.png");

    final int imageCount = _assetList.length;
    final int maxTime = interval * imageCount;

    // 启动动画controller
    _controller = new AnimationController(
        duration: Duration(milliseconds: maxTime), vsync: this);
    _controller?.addStatusListener((AnimationStatus status) {
      if (status == AnimationStatus.completed) {
        _controller?.forward(from: 0.0); // 完成后重新开始
      }
    });

    _animation = new Tween<double>(begin: 0, end: imageCount.toDouble())
        .animate(_controller!)
          ..addListener(() {
            setState(() {});
          });

    _init();

    ///初始化方法的监听
    // recordPlugin?.responseFromInit.listen((data) {
    //   if (data) {
    //     print("初始化成功");
    //   } else {
    //     print("初始化失败");
    //   }
    // });

    /// 开始录制或结束录制的监听
    // recordPlugin?.response.listen((data) {
    //   if (data.msg == "onStop") {
    //     ///结束录制时会返回录制文件的地址方便上传服务器
    //     // print("onStop  " + data.path);
    //     if (!TextUtil.isEmpty(data.path) && (data.audioTimeLength??0) > 0) {
    //       if(widget.stopRecord!=null){
    //         widget.stopRecord!(data.path, data.audioTimeLength);
    //       }
    //
    //       setState(() {
    //         _voicePath = data?.path??"";
    //         _audioTimeLength = data.audioTimeLength??0;
    //       });
    //     }
    //   } else if (data.msg == "onStart") {
    //     print("onStart --");
    //     if(widget.startRecord!=null){
    //       widget.startRecord!();
    //     }
    //   }
    // });
    //
    // ///录制过程监听录制的声音的大小 方便做语音动画显示图片的样式
    // recordPlugin?.responseFromAmplitude.listen((data) {
    //   var voiceData = double.parse(data.msg??"");
    //   setState(() {
    //     if (voiceData > 0 && voiceData < 0.1) {
    //       voiceIco = "assets/voice_volume_2.png";
    //     } else if (voiceData > 0.2 && voiceData < 0.3) {
    //       voiceIco = "assets/voice_volume_3.png";
    //     } else if (voiceData > 0.3 && voiceData < 0.4) {
    //       voiceIco = "assets/voice_volume_4.png";
    //     } else if (voiceData > 0.4 && voiceData < 0.5) {
    //       voiceIco = "assets/voice_volume_5.png";
    //     } else if (voiceData > 0.5 && voiceData < 0.6) {
    //       voiceIco = "assets/voice_volume_6.png";
    //     } else if (voiceData > 0.6 && voiceData < 0.7) {
    //       voiceIco = "assets/voice_volume_7.png";
    //     } else if (voiceData > 0.7 && voiceData < 1) {
    //       voiceIco = "assets/voice_volume_7.png";
    //     } else {
    //       voiceIco = "assets/voice_volume_1.png";
    //     }
    //     if (overlayEntry != null) {
    //       overlayEntry?.markNeedsBuild();
    //     }
    //   });
    //
    //   print("振幅大小   " + voiceData.toString() + "  " + voiceIco);
    // });
    //
    // ///播放状态
    // recordPlugin?.responsePlayStateController.listen((data) {
    //   print("播放路径   " + data.playPath);
    //   print("播放状态   " + data.playState);
    //   if (data.playState == 'complete') {
    //     setState(() {
    //       isAnimation = false;
    //     });
    //   }
    // });
  }

  ///显示录音悬浮布局
  buildOverLayView(BuildContext context) {
    if (overlayEntry == null) {
      overlayEntry = new OverlayEntry(builder: (content) {
        return Positioned(
          top: MediaQuery.of(context).size.height * 0.5 - 80,
          left: MediaQuery.of(context).size.width * 0.5 - 80,
          child: Material(
            type: MaterialType.transparency,
            child: Center(
              child: Opacity(
                opacity: 0.8,
                child: Container(
                  width: 160,
                  height: 160,
                  decoration: BoxDecoration(
                    color: Color(0xff77797A),
                    borderRadius: BorderRadius.all(Radius.circular(20.0)),
                  ),
                  child: Column(
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(top: 10),
                        child: new Image.asset(
                          voiceIco,
                          width: 100,
                          height: 100,
                        ),
                      ),
                      Container(
//                      padding: EdgeInsets.only(right: 20, left: 20, top: 0),
                        child: Text(
                          toastShow,
                          style: TextStyle(
                            fontStyle: FontStyle.normal,
                            color: Colors.white,
                            fontSize: 14,
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      });
      Overlay.of(context).insert(overlayEntry!);
    }
  }

  showVoiceView() {
    setState(() {
      textShow = "松开结束";
      voiceState = false;
    });
    buildOverLayView(context);
    start();
  }

  hideVoiceView() {
    setState(() {
      textShow = "按住说话";
      voiceState = true;
    });

    stop();
    if (overlayEntry != null) {
      overlayEntry?.remove();
      overlayEntry = null;
    }

    if (isUp) {
      print("取消发送");
    } else {
      print("进行发送");
    }
  }

  moveVoiceView() {
    // print(offset - start);
    setState(() {
      isUp = starty - offset > 100 ? true : false;
      if (isUp) {
        textShow = "松开手指,取消发送";
        toastShow = textShow;
      } else {
        textShow = "松开结束";
        toastShow = "手指上滑,取消发送";
      }
    });
  }

  ///初始化语音录制的方法
  void _init() async {
    // recordPlugin?.init();
  }

  ///开始语音录制的方法
  void start() async {
    // recordPlugin?.start();
  }

  ///停止语音录制的方法
  void stop() {
    // recordPlugin?.stop();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> images = [];
    if (isAnimation) {
      _animationStart();
      int ix = _animation!.value.floor() % _assetList.length;
      // 把����������有图片都加载进内容，否则每一帧加载时会卡顿
      for (int i = 0; i < _assetList.length; ++i) {
        if (i != ix) {
          images.add(Image.asset(
            _assetList[i],
            width: 0,
            height: 0,
            color: Colors.white,
          ));
        }
      }
      images.add(
        Image.asset(
          _assetList[ix],
          width: 30,
          height: 30,
          color: Colors.white,
        ),
      );
    } else {
      _animationStop();
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        SizedBox(
          height: _audioTimeLength > 0 ? 40 : 0,
          width: min(200, _audioTimeLength * 20 + 50),
          child: InkWell(
            onTap: () {
              setState(() {
                isAnimation = true;
              });
              // recordPlugin?.playByPath(_voicePath, "file");
            },
            child: Container(
              decoration: BoxDecoration(
                color: Colors.orange[200],
                borderRadius: BorderRadius.circular(5),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: isAnimation
                        ? images
                        : [
                            Image.asset(
                              _assetList[2],
                              width: 30,
                              height: 30,
                              color: Colors.white,
                            ),
                          ],
                  ),
                  Gaps.hGap10,
                  Text(
                    '$_audioTimeLength "',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
        _audioTimeLength > 0 ? SizedBox(height: 12.0) : SizedBox(),
        Container(
          width: double.infinity,
          height: 50,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: Colours.app_main,
            borderRadius: BorderRadius.circular(10.0),
          ),
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onLongPressStart: (details) {
              starty = details.globalPosition.dy;
              print("start------onLongPressStart");
              showVoiceView();
            },
            onLongPressEnd: (details) {
              hideVoiceView();
              print("end------onLongPressEnd");
            },
            onLongPressMoveUpdate: (details) {
              offset = details.globalPosition.dy;
              moveVoiceView();
              print("update------onLongPressMoveUpdate");
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.keyboard_voice,
                  color: Colors.white,
                  size: 30,
                ),
                Text(
                  '长按录音',
                  style: TextStyle(
                    fontSize: 18,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
